package com.example.service.impl;

import com.example.common.AppResult;
import com.example.common.ResultCode;
import com.example.dao.ArticleMapper;
import com.example.exception.ApplicationException;
import com.example.model.Article;
import com.example.model.Board;
import com.example.model.User;
import com.example.service.IArticleService;
import com.example.service.IBoardService;
import com.example.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: bjc
 * Date: 2025-10-10
 * Time: 21:42
 */
@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private IUserService userService;
    @Autowired
    private IBoardService boardService;


    /**
     * 创建帖子
     * @param article 帖子信息
     */
    @Override
    public void createArticle(Article article) {
        //1.非空校验,帖子标题和内容不能为空;同时帖子需要关联板块和用户
        if(article == null || article.getUserId() == null || article.getBoardId() == null
        || StringUtils.isEmpty(article.getTitle())
        || StringUtils.isEmpty(article.getContent())){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.设置帖子默认属性
        article.setVisitCount(0);//访问量
        article.setReplyCount(0);//回复数
        article.setLikeCount(0);//点赞数
        article.setState((byte) 0);//帖子状态，0正常，1禁用
        article.setDeleteState((byte) 0);//帖子删除状态，0正常，1禁用
        Date now = new Date();
        article.setCreateTime(now);
        article.setUpdateTime(now);
        //3.插入帖子信息到数据库中
        int insertCount = articleMapper.insertSelective(article);
        if(insertCount <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        log.info("创建帖子成功，article="+article);
        //4.更新对应用户的发帖数
        //4.1根据用户id查询用户信息
        User user = userService.selectById(article.getUserId());
        if(user == null){
            //打印日志
            log.warn(ResultCode.FAILED_CREATE.toString()+",发帖失败，用户id为："+article.getUserId());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //4.2更新用户发帖数
        userService.addOneArticleCountById(user.getId());
        //5.更新对应板块下的帖子数
        //5.1根据板块id查询板块信息
        Board board = boardService.selectById(article.getBoardId());
        if(board == null){
            //打印日志
            log.warn(ResultCode.FAILED_CREATE.toString()+",发帖失败，板块id为："+article.getBoardId());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //5.2更新板块下的帖子数
        boardService.addOneArticleCountById(board.getId());
        log.info("发帖成功，帖子对应的用户id:"+article.getUserId()+",板块id:"+article.getBoardId());

    }

    /**
     * 查询所有帖子
     * @return 所有帖子信息
     */
    @Override
    public List<Article> selectAll() {
       //1.查询所有帖子信息
        List<Article> articleList = articleMapper.selectAll();
        //2.返回结果
        return articleList;
    }

    /**
     * 根据板块id查询帖子列表
     * @param boardId 板块id
     * @return 帖子列表
     */
    @Override
    public List<Article> selectByBoardId(Long boardId) {
        //1.非空校验
        if(boardId == null){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.校验板块是否存在
        Board board = boardService.selectById(boardId);
        if(board == null){
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        //3.根据板块id查询帖子列表
        List<Article> articleList = articleMapper.selectByBoardId(boardId);
        //4.返回结果
        return articleList;
    }
    /**
     * 根据帖子id查询帖子详情
     * @param articleId 帖子id
     * @return 帖子详情
     */
    public Article selectDetailById(Long articleId) {
        // 向后兼容：默认增加访问数
        return selectDetailById(articleId, true);
    }

    public Article selectDetailById(Long articleId, boolean increaseVisit) {
        //1.非空校验
        if(articleId == null || articleId <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.根据帖子id查询帖子详情
        Article article = articleMapper.selectDetailById(articleId);
        if(article == null){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //3.判断帖子状态，使得如果帖子是处于删除状态或者禁用状态，则不能访问
        if((article.getState() != null && article.getState() == 1) ||
                (article.getDeleteState() != null && article.getDeleteState() == 1)){
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }

        // 只有在需要增加访问数时才更新数据库
        if (increaseVisit) {
            Article updateArticle = new Article();
            updateArticle.setId(article.getId());
            updateArticle.setVisitCount(article.getVisitCount() + 1);
            int updateCount = articleMapper.updateByPrimaryKeySelective(updateArticle);
            if(updateCount <= 0){
                log.warn(ResultCode.ERROR_SERVICES.toString() + " articleId=" + updateArticle.getId());
                throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
            }
            // 确保返回对象的访问数是更新后的值
            article.setVisitCount(article.getVisitCount() + 1);
        }

        return article;
    }
/**
 * 根据帖子id查询帖子详情
 * @param ArticleId 帖子id
 * @return 帖子详情
 */
/*@Override
public Article selectDetailById(Long ArticleId) {
    //1.非空校验
    if(ArticleId == null || ArticleId <= 0){
        //打印日志
        log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        //抛出异常
        throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
    }
    //2.根据帖子id查询帖子详情
    Article article = articleMapper.selectDetailById(ArticleId);
    if(article == null){
        //打印日志
        log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
        //抛出异常
        throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
    }
    //3.帖子存在，更新帖子访问数
    Article updateArticle = new Article();
    updateArticle.setId(article.getId());
    updateArticle.setVisitCount(article.getVisitCount()+1);
    //更新到数据库中存储
    int updateCount = articleMapper.updateByPrimaryKeySelective(updateArticle);
    if(updateCount <= 0){
        //打印日志
        log.warn(ResultCode.ERROR_SERVICES.toString()+"articleId="+updateArticle.getId());
        //抛出异常
        throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
    }
    //4.更新帖子数，确保返回给控制层的article的访问数是修改后的。
    article.setVisitCount(article.getVisitCount()+1);

    //5.返回结果
    return article;
}*/


    /**
     * 修改帖子
     * @param id 帖子id
     * @param title 帖子标题
     * @param content 帖子内容
     */
    @Override
    public void modifyArticleById(Long id, String title, String content) {
        //1.非空校验
        if(id == null || id <= 0 || StringUtils.isEmpty(title) || StringUtils.isEmpty(content)){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.构造帖子对象
        Article article = new Article();
        article.setId(id);
        article.setTitle(title);
        article.setContent(content);
        article.setUpdateTime(new Date());
        //3.更新帖子
        int updateCount = articleMapper.updateByPrimaryKeySelective(article);
        if(updateCount != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString()+"articleId="+article.getId());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    /**
     * 根据id查询帖子
     * @param id 帖子id
     * @return 帖子对象
     */
    @Override
    public Article selectById(Long id) {
        //1.非空校验
        if(id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.根据id查询帖子
        Article article = articleMapper.selectByPrimaryKey(id);
        return article;
    }

    /**
     * 点赞
     * @param id 帖子id
     */
    @Override
    public void thumbsUpById(Long id) {
       //1.非空校验
       if(id == null || id <= 0){
           //打印日志
           log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
           //抛出异常
           throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
       }
       //2.根据id查询帖子状态
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article == null){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if(article.getState() == 1 || article.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }

        //3.构造帖子对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setLikeCount(article.getLikeCount()+1);
        updateArticle.setUpdateTime(new Date());

        //4.更新帖子
        int updateCount = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(updateCount != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString()+"articleId="+updateArticle.getId());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    /**
     * 删除帖子
     * @param id 帖子id
     */
    @Override
    @Transactional
    public void deleteById(Long id) {
        //1.非空校验
        if(id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.根据id查询帖子
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article == null){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //3.帖子存在，但是帖子状态异常，则不允许删除
        if((article.getState() != null && article.getState() == 1) ||
                (article.getDeleteState() != null && article.getDeleteState() == 1)){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //4.构造帖子对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setDeleteState((byte) 1);
        updateArticle.setUpdateTime(new Date());
        //5.更新帖子
        int updateCount = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(updateCount != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString()+"articleId="+updateArticle.getId());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //6.更新帖子所属板块的帖子数
        boardService.subOneArticleCountById(article.getBoardId());
        //7.更新用户发帖数
        userService.subOneArticleCountById(article.getUserId());
        log.info("删除帖子成功，articleId="+id+",userId="+article.getUserId());
    }
    /**
     * 帖子回复数+1
     * @param id 帖子id
     */
    @Override
    public void addOneArticleReplyCountById(Long id) {
        //1.非空校验
        if(id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.根据id查询帖子
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article == null){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //3.帖子存在，但是帖子状态异常，则不允许操作
        if((article.getState() != null && article.getState() == 1) ||
                (article.getDeleteState() != null && article.getDeleteState() == 1)){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //4.构造帖子对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setReplyCount(article.getReplyCount()+1);
        updateArticle.setUpdateTime(new Date());
        //5.更新帖子
        int updateCount = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(updateCount != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString()+"articleId="+updateArticle.getId());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    /**
     * 根据用户id查询所发的帖子列表
     * @param userId 用户id
     * @return
     */
    @Override
    public List<Article> selectByUserId(Long userId) {
        //1.非空校验
        if(userId == null || userId <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.判断用户是否存在
        User user = userService.selectById(userId);
        if(user == null){
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //3.调用DAO层查询对应的帖子列表
        List<Article> articleList = articleMapper.selectByUserId(userId);
        //4.返回结果
        return articleList;
    }
}
